<?php
namespace objectpool;

use Countable;

class ObjectPool implements Countable { //Countable是PHP自带接口类，有一个方法count()

    private static $busyObject = []; //使用中的对象池
    private static $freeObject = []; //空闲未使用的对象池

    public static function get() 
    {
        if(0 === count(self::$freeObject)) {
            $object = new ObjectA(); //可以结合工厂模式做类的实例化
        } else {
            $object = array_pop(self::$freeObject); //从对象池中取用一个对象，弹出并返回数组中最后一个元素，并将数组的长度减1
        }
        self::$busyObject[spl_object_hash($object)] = $object; //对象取出使用前，将这个对象放入使用中的对象池
        return $object;
    }

    public static function dispose($object) 
    {
        $key = spl_object_hash($object); //将对象哈希一下返回一个唯一标识符
        if(isset(self::$busyObject[$key])) {
            unset(self::$busyObject[$key]);
            self::$freeObject[$key] = $object;
        }

    }

    //观察测试
    public static function see()
    {
        echo "使用中的对象：\n";
        if(count(self::$busyObject) > 0) {
            foreach(self::$busyObject as $k => $v) {
                echo (string)$k, "\n";
            }
        } else {
            echo "无\n";
        }
        
        echo "空闲中的对象：\n";
        if(count(self::$freeObject) > 0) {
            foreach(self::$freeObject as $k => $v) {
                echo (string)$k, "\n";
            }
        } else {
            echo "无\n";
        }
        
    }

    public function count() : int
    {
        return count(self::$freeObject) + count(self::$busyObject);
    }

}